package com.epoque.common.util;

import java.util.ArrayList;
import java.util.List;

import com.epoque.common.vo.TreeNode;

/**
 * 
 * @ClassName: TreeUtil
 * @Description: 树操作工具类
 * @author qiuxianfeng
 * @date 2018年8月29日
 *
 */
public class TreeUtil{
	
  /**
   * 	
   * @Title: bulid
   * @author qiuxianfeng
   * @Description: 两层循环实现建树
   * @param @param treeNodes  传入的树节点列表
   * @param @param root
   * @param @return    参数
   * @return List<T>    返回类型
   * @throws
   */
  public static <T extends TreeNode> List<T> bulid(List<T> treeNodes,Object root) {

    List<T> trees = new ArrayList<T>();

    for (T treeNode : treeNodes) {

      if (root.equals(treeNode.getParentId())) {
        trees.add(treeNode);
      }

      for (T it : treeNodes) {
        if (it.getParentId() == treeNode.getId()) {
          if (treeNode.getChildren() == null) {
            treeNode.setChildren(new ArrayList<TreeNode>());
          }
          treeNode.add(it);
        }
      }
    }
    return trees;
  }

  /**
   * 
   * @Title: buildByRecursive
   * @author qiuxianfeng
   * @Description: 使用递归方法建树
   * @param @param treeNodes
   * @param @param root
   * @param @return    参数
   * @return List<T>    返回类型
   * @throws
   */
  public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes,Object root) {
    List<T> trees = new ArrayList<T>();
    for (T treeNode : treeNodes) {
      if (root.equals(treeNode.getParentId())) {
        trees.add(findChildren(treeNode, treeNodes));
      }
    }
    return trees;
  }

  /**
   * 
   * @Title: findChildren
   * @author qiuxianfeng
   * @Description: 递归查找子节点
   * @param @param treeNode
   * @param @param treeNodes
   * @param @return    参数
   * @return T    返回类型
   * @throws
   */
  public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
    for (T it : treeNodes) {
      if (treeNode.getId() == it.getParentId()) {
        if (treeNode.getChildren() == null) {
          treeNode.setChildren(new ArrayList<TreeNode>());
        }
        treeNode.add(findChildren(it, treeNodes));
      }
    }
    return treeNode;
  }

}
